<!--  CSS specific to this page -->
<style>
.itemicon {
    display : none
    }  
.responseslider {
    height: 3px;
}
li.respond.hdr {
    width:100%;
    /*background-color:LightYellow;*/
    margin-bottom:1em;
    }
li.respond {
    width:100%;
    background-color:LightYellow;
    /*margin-bottom:1em; */
    }
ul.itemrow {
    list-style-type:none;
    margin-bottom:2em;
    width:90%
}
ul.respond {
    list-style-type:none;
    margin-bottom:2em;
    width:90%
    }        
div.slider_wrapper {
    width: 200px;
    text-align:center;
    padding-top:5px;
    }
ul.results {
    list-style-type:none;
    margin-bottom:2em;
    width:90%;
    }
ul.itemrow {
    width:90%;
    }
.resultdetails {
    display:none;
    }
li.respond.slider {
    width:100%;
    /* background-color:LightYellow;*/
    margin-bottom:1em;
    }
td.inset {
    /* width of solution histogram */
    width: {{='4em' if mode == 'RESULTS' else '32px' }};
    }
td.sliderendbtn {
    vertical-align: top;
    }

#readout {
    width: 25em;
    position: relative;
    }
table.comments {
    width: 100%;
    }
td.comments {
    }

.commententry {
    padding-left: 0;
    display: none;
    }              

.ui_slider {
    -webkit-touch-callout:none;
    }

.ui_slider_handle {
    -webkit-touch-callout:none;
    }

.sliderendbtn {
    /* on iPhone, prevent save image sheet from appearing */
    -webkit-touch-callout:none;
    }
</style>  

{{
## -------------- PYTHON PRELIMINARIES ------------------
def emptyli():
    return XML("""<li><table><tr></tr></table></li>""")

def solutionhistogram(sid,h):
    html = """
            <td id="%(sid)scountpie" class=countpie> </td>
            <td id="%(sid)s"  
                class="barhist inset clickable"
                onclick="$('.%(sid)sdetails').toggle();
                $.sparkline_display_visible(); 
                ">
                %(h)s
            </td>            
    """%locals()
    return XML(html)

def solutiondetailheader(sid):
    html = """
            <!-- Header for detail histograms for %(sid)s -->
            <li class="resultdetails %(sid)sdetails"> <table> <tr>
                    <td class="inset"></td>
                    <td class=hidden></td>
                    <td><small>Weighted</small></td>
                    <td><small>Raw</small></td>
                    <td></td>
            </tr> </table> </li> 
    """%locals()
    return XML(html)   

def solutiondetailhistogram(sid,hid,h,hraw,cobj):
    label = mklabel(cobj.text)
    html = """
            <!-- Detail histograms for %(sid)s -->
            <li class="resultdetails %(sid)sdetails"> <table> <tr>
                    <td class="inset"></td>
                    <td class=hidden></td>
                    <td id="%(hid)s">%(h)s</td>
                    <td id="%(hid)s_raw">%(hraw)s</td>
                    <td>%(label)s</td>
            </tr> </table> </li> 
    """%locals()
    return XML(html)

def icontd(icon,iconislink):
    if iconislink:
        return TD(icon)
    else:
        return TD(IMG(_src=icon))
        pass

def edititemicon(icon,iteminfo):
    newitem = iteminfo['itemtype'].startswith('new')
    if session.problemisembryo or newitem: 
        ## make an edit link
        if newitem:
            iconclass = "newitemicon"
        else:
            iconclass ="olditemicon"
            pass
        itemicon = A(IMG(_src=icon, _class=iconclass),
                 _href=URL(r=request, f="edititem", vars=iteminfo)
                 )
        return (itemicon, True)
    else:
        return (icon,False)
        pass


def solutionrow(sid,h,icon,sobj,iconislink=False):
    if h:
        left = solutionhistogram(sid,h)
    else:
        left = icontd(icon,iconislink)
        pass
    return itemrow(sid,left,sobj)

def criterionrow(cid,h,icon,cobj,iconislink=False):
    if h:
        left = """
        <td id="%(cid)scountpie"></td>    
        <td id="%(cid)s" class="inset clickable">%(h)s</td>
        """%locals()
    else:
        left = icontd(icon,iconislink)
        pass
    return itemrow(cid,left,cobj)     

def pagetitlerow(left,right):
    html = """
        <table><tr>
        %(left)s
        %(right)s
        </tr></table>
        """%locals()
    return XML(html)    

def problemrow(icon, obj,iconislink=False):
    left = icontd(icon,iconislink)
    return itemrow("problem",left,obj)

def itemrow(id,left,obj):
    try:
        label = mklabel(obj.text)
    except AttributeError:
        label = obj.text
        pass  
    
    if isinstance(obj,Storage):
        # It's just a label for a new item
        # so don't make it clickable because
        # it doesn't have fulltext or comments.
        tdclass = "itemlabel"
        onclick = ""
    else:
        tdclass = "clickable itemlabel"
        onclick = "$('#%(id)sfulltext').toggle()"%locals()
        pass
    html = """
        <li><table><tr>
            %(left)s
            <td class="%(tdclass)s" onclick="%(onclick)s">
            %(label)s
            <td>
        </tr></table></li>"""%locals()
    return XML(html)

def fulltextwithcomments(id,obj,widget=None):
    fulltext = myXML(obj.text)

    entryblock = ""
    if widget:
        entryblock = """
            <tr>
                <td class="inset"></td>
                <td id="%(id)scommententry"
                    class=commententry>%(widget)s</td>
            </tr>
            """%locals()
        pass

    ncmts = len(obj.comments[0])
    cmtstr = "%d "%ncmts + plrl(ncmts, PT['T']['comment'], PT['T']['comments'])
    html = """
    <li id="%(id)sfulltext" class="hidden"> 
        <table> 
            <tr>
                <td class="inset"></td>
                <td><div style="{width:40em;}">%(fulltext)s</div>
                    <span id="%(id)scommentlink" 
                        class="clickable commentlink"
                        onclick="itemcomments('%(id)s',
                            '%(id)scomments',
                            this.id,
                            '%(id)scommententry')">
                        %(cmtstr)s 
                    </span>
                </td>
            </tr>
            <tr>
                <td class="inset"></td>
                <td class="comments" id="%(id)scomments"></td>
            </tr> 
            %(entryblock)s
        </table> 
    </li> 
    """%locals()
    return XML(html)

def responseslider(inp,inpid,label): 
    sliderminusicon = URL(r=request, c='static', f="zminsmbl.gif")
    sliderplusicon = URL(r=request, c='static', f="zplssmrd.gif")
    sliderid = "slider_%s"%inpid
    sliderlabelid = "%s_val"%sliderid
    plusbtnid = "%s_plus"%sliderid
    minusbtnid = "%s_minus"%sliderid
    inpval = inp['_value']
    html = """
         <li class=respond.slider>
            <table class=respond> 
                <tr> 
                    <td class="inset"></td>
                    <td class="sliderendbtn">
                        <span>
                        <img id="%(minusbtnid)s" 
                            src="%(sliderminusicon)s"
                            class="sliderendbtn"
                            onclick="noDefault(event);"
                        >
                        </span>
                     </td>
                         <td>
                        <div class="slider_wrapper">
                            %(inp)s 
                            <div id="%(sliderid)s" class="responseslider" 
                                onclick="noDefault(event);"
                            ></div>
                                <span id="%(sliderlabelid)s">%(inpval)s</span>
                            </div>
                        </td>
                    <td class="sliderendbtn">
                        <span>
                        <img id="%(plusbtnid)s" 
                            src="%(sliderplusicon)s" 
                            class="sliderendbtn"
                            onclick="noDefault(event);"
                            >
                        </span>
                     </td>
                    <td>%(label)s</td>
                </tr>
            </table>
        </li> 
        """%locals()
    return XML(html)

def deletionbox(delbox):
    label = T('Recommend for deletion?')
    html = """
        <li class=respond.slider>
            <table>
                <tr>
                    <td class=inset></td>
                    <td>
                        %(delbox)s&nbsp;<em>%(label)s</em>
                    </td>
                </tr>
            </table>
        </li>         
    """%locals()

    return XML(html)

syns = problem.getSynonyms() or PTCFG.synonyms

## short names for useful methods
hist = ptproblem.hist
mklabel = ptproblem.mkLabel

sorted = problem.sortSolutionsReverseChrono()
csorted = problem.sortCriteriaReverseChrono()
bulbicon = URL(r=request, c="static", f="lightbulb32.png")
downloadicon = URL(r=request, c="static", f="downloadicon.png")
gaugeicon = URL(r=request, c='static', f="gauge.png")
problemicon = URL(r=request, c='static', f="rubik32.png")


nparticipants = len(problem.lastresponses)

if mode == "RESULTS":
    ## On entry, vars returned by controller are
    ## problem, c, s, sc, wsc, problemid, nparticipants


    solutionorder = [sid for (sid,score) in problem.srankings]
    srankdict = dict()
    for sid,score in problem.srankings:
        srankdict[sid] = score
        pass

    crankdict = dict()
    criteriaorder = [cid for (cid, score) in problem.crankings]
    for cid, score in problem.crankings:
        crankdict[cid] = score
        pass

    ## Y-limits of sparkline bar chart histograms
    chartmin=0
    chartmax=nmax   ## Keeps all charts consistent 
                    ## but avoids tiny bars when there 
                    ## are few responses

    ## Composite object we pass into JS via JD().
    PT = getPT(extensions = dict(
        mode = mode,
        pagehelp = """
        <h3>Page Help</h3>
        <ul>
        <li>
        Click title to toggle result details. Double-click forces all result details to be shown.
        </li><li>
        Click bar graphs to show/hide individual result details. 
        </li><li>
        Click %s, %s, and %s  titles to show/hide full text of items.
        </li> 
        </ul>
        """%(syns['problem'], syns['solution'], syns['criterion']),
        s = s,
        c = c,
        wsc = wsc,
        updatenow=False,
        schartoptions = dict(
            type ='bar',
            colorMap = ['blue','blue','blue','blue','grey','red','red','red','red'],
            chartRangeMin = chartmin,
            chartRangeMax = chartmax,
            ),

        countpieoptions = dict(
            type = 'pie',
            sliceColors = ['black', 'green', 'white'],
            offset = -90,
            chartRangeMin = chartmin, 
            chartRangeMax = chartmax,
            ),

        cchartoptions = dict(
            type = 'bar', 
            barColor = 'black', 
            chartRangeMin = chartmin, 
            chartRangeMax = chartmax,
            ), 
        cbdict = dict(), #storage for things used in callbacks.

                                            # sparkline updates.
        lastmodified = problem.lastmodified,
        lastresponse = 0.0,                 # min(lastresponses.values)
    ));
elif mode == "RESPOND":
    solutionorder = [sid for (sid,s) in sorted]
    criteriaorder = [cid for (cid,c) in csorted]
    FCW = form.custom.widget
    PT = getPT(extensions = dict(
            mode = mode,
            solutionsliderinputs = [],
            criterionsliderinputs = [],
            )
        )

elif mode == "EDIT":
    solutionorder = [sid for (sid,s) in sorted]
    criteriaorder = [cid for (cid,c) in csorted]
    PT = getPT(extensions = dict(
    mode = mode,
    ))

pass #if mode

## ------------  END PYTHON PRELIMINARIES ------------- 
}}

<!--  BEGIN PAGE MARKUP  -->
{{
if mode == "RESULTS":
    icon = problemicon
    iconislink = False
    beginform = ""
    endform = ""
    hleft = """
   <td><h1 id="pagetitle" class="clickable">%s</h1></td>
    """%T("Results")

    respfrom =  T('responses from') 
    particip = T('participants.')
    secuntil = T('Seconds until next update:')
    hright = """
    <td>
        <div id='readout' class="clickable"  onclick="PT.updatenow=true;">
        <i id='nresponses'>0</i><i> %s </i>
        <i id=nparticipants>0</i><i> %s</i><br>    
        <i> %s </i><i id="updatecountdown">0</i> <br>
        </div>
    </td>
    """%(respfrom, particip, secuntil)

    addcmt = None

elif mode == "RESPOND":
    icon = problemicon
    iconislink = False
    beginform = form.custom.begin
    endform   = form.custom.end
    hleft = """
    <td><h1 id="pagetitle" class="clickable">%s</h1></td>
    """%T('Respond')
    hright = ""
    addcmt = FCW['addcommentproblem']

elif mode == "EDIT":
    iteminfo = {'itemtype':'description', 'itemid':str(0)}
    icon,iconislink = edititemicon(problemicon, iteminfo)
    beginform = ""
    endform = ""
    hleft = """
    <td><h1 id="pagetitle" class="clickable">%s</h1></td>
    """%T('Edit')
    hright = ""
    addcmt = None
    pass

=pagetitlerow(hleft,hright)
=beginform
}}
<ul class="itemrow">
    {{=problemrow(icon, problem, iconislink=iconislink)}}
    {{=fulltextwithcomments("problem",problem,addcmt)}}
    <li class=respond><h2>
    {{=syns["Solutions"]}}
    </h2></li>

<!-- Solution Section -->
{{
if mode == 'EDIT':
    iteminfo = {'itemtype':"new_solution", 'itemid':str(0)}
    icon,iconislink = edititemicon(bulbicon, iteminfo)
    obj = Storage(text=B(T("New")))
    =solutionrow(0,None,icon,obj,iconislink=True)
    pass

for sid in solutionorder:
    sobj = problem.solutions[sid]
    if mode == "RESULTS":
        score = srankdict[sid]
        detid = sid+"details"
        r = s[sid]
        h = ','.join([str(x) for x in hist(r)]) if r!=None else ''
        addcmt = None
        icon = None
        iconislink = False
    elif mode == "RESPOND":
        delbox = FCW['del%s'%sid]
        addcmt = FCW['addcomment%s'%sid]
        h = None
        icon = bulbicon
        iconislink = False
    elif mode == "EDIT":
        iteminfo = {'itemtype':'solution', 'itemid':sid}
        icon,iconislink = edititemicon(bulbicon, iteminfo)
        h = None
    pass

    =solutionrow(sid,h,icon,sobj,iconislink=iconislink)
    =solutiondetailheader(sid)
    for cid in criteriaorder:
        cobj = problem.criteria[cid]
        if mode == "RESULTS":
            score = crankdict[cid]
            r = wsc[sid][cid]
            h = ','.join([str(x) for x in hist(r)]) if r!=None else ''
            r = sc[sid][cid]
            hraw = ','.join([str(x) for x in hist(r)]) if r!=None else ''
            hid = sid + cid
            inp = dict(_value="") 
            inpid = hid
            label = ""
            =solutiondetailhistogram(sid,hid,h,hraw,cobj)
        elif mode == "RESPOND":
            ## lay out the sliders and criteria text
            inp = FCW["%s_%s"%(sid,cid)]
            label = mklabel(cobj.text)
            inpid = inp['_id']
            PT['solutionsliderinputs'].append(inpid)
            =responseslider(inp,inpid,label)  
            pass
        pass

    if mode == "RESPOND" and len(solutionorder) > 1:    
        =deletionbox(delbox) 
        pass 


    =fulltextwithcomments(sid,sobj,addcmt)
    
    pass
}}    


<li class=respond> <h2>
{{=syns["Criteria"]}}
</h2> </li>
{{
if mode == 'EDIT':
    iteminfo = {'itemtype':"new_criterion", 'itemid':str(0)}
    icon,iconislink = edititemicon(gaugeicon, iteminfo)
    obj = Storage(text=B(T("New")))
     =criterionrow(0,None,icon,obj,iconislink=True)
    pass

for cid in criteriaorder:
    cobj = problem.criteria[cid]
    icon = None
    iconislink = False
    if mode == "RESULTS":
        inpid = ""  
        r = c[cid]
        h = ','.join([str(x) for x in hist(r,nbins=5,twosided=False)]) if r!=None else ''

    elif mode == "RESPOND":
        ## lay out the sliders and criteria text
        delbox = FCW['del%s'%cid]
        addcmt = FCW['addcomment%s'%cid]
        icon = gaugeicon
        h = None
        inp = FCW[cid]
        inpid = inp['_id']
        PT['criterionsliderinputs'].append(inpid)

    elif mode == "EDIT":
        iteminfo = {'itemtype':'criterion', 'itemid':cid}
        icon = A(IMG(_src=gaugeicon),
                 _href=URL(r=request, f="edititem", vars=iteminfo)
                 )
        iconislink = True
        h = None
        pass
        
    =criterionrow(cid,h,icon,cobj,iconislink=iconislink)  
    if mode == "RESPOND":
        =responseslider(inp,inpid,"")
        if len(criteriaorder) > 1:
            =deletionbox(delbox)
            pass
        pass
    =fulltextwithcomments(cid,cobj,addcmt)    
    pass
if mode == "RESPOND":
    =LI(form.custom.submit)
    =form.custom.end
elif mode == "RESULTS":
    csvurl = URL(r=request, c='getdata', f='index')
    =LI(XML("&nbsp;"))
    
    link = A(IMG(_src=downloadicon), _href=csvurl)
    label = H2(EM(T("Download results as CSV")))
    =LI(TABLE(TR(TD(link),TD(label))))
    pass
}}


</ul>
<script type="text/javascript">
    /* <![CDATA[ */
    // Info passed at render time
    var PT = {{=JD(PT)}};

    function pievalues(nparticipants, nresponses, ndelvotes) {
        // computes wedge values for pie chart
        assert(nparticipants >= nresponses, 'Too many responses!');
        assert(nresponses >= ndelvotes, 'Too many votes for deletion!');
        var w1 = ndelvotes;
        var w2 = nresponses - ndelvotes;
        var w3 = nparticipants - nresponses;
        return [w1, w2, w3]
        };

    function countpietip(a,b,c,d){
        return ("<p>"
                + PT.T.responses + " " 
                + a.toString() 
                + "</p><p>"
                + PT.T.votesfordeletion + " " + d.toString() 
                + "</p>");
        };

    function solutionbartip(score){
        return ("<p>Mean favorability: " + score
                + "</p><p>Click to show/hide details.</p>");
        };

    function noDefault(event) {
        event.preventDefault();
        //console.log("Prevented "+event.type+" on "+event.target.id);
        };

    function sliderinit(inpid,min,max) {
        var sldid = '#slider_'+inpid; 
        var sldlblid = sldid + "_val"
        inpid = '#'+inpid;
        $(inpid).hide();
        $(sldid).slider(
            {
            min:    min,
            max:    max,
            step:   (max-min)/100.,
            value:  $(inpid).val(),

            stop:   function(event,ui) {
                    $(inpid).val(ui.value);
                    $(sldlblid).text((ui.value).toFixed(2));
                    }
            });
        if (PT.isiOS == true) {
            // Suppress iPhone view scrolling
            $(sldid).slider().bind("touchstart touchmove touchend",noDefault);
            knob = $(sldid).slider().children()[0];
            $(knob).bind("touchstart touchmove touchend",noDefault);
            };

        // define custom slider events 'incr' and 'decr'
        $(sldid).slider().bind("incr decr",{
            max:max, 
            min:min,
            slid:$(sldid).slider(),
            inpid:inpid,
            labelid:$(sldlblid),
            }, function(e) {
                var d = e.data;
                var v = d.slid.slider("value");
                var sign;
                (e.type == "decr") ? sign = -1.0 : sign = 1.0;
                var vf = parseFloat(v);
                vf += sign * d.slid.slider("option","step");
                if (vf > d.max) vf = d.max;
                else if (vf < d.min) vf = d.min;
                $(d.inpid).val(vf);
                d.slid.slider("value",vf);
                $(d.labelid).text(vf.toFixed(2));
                }
            );

        // Arrange for clicks on + and - images to 
        // trigger custom slider events
        var plus = sldid + "_plus";
        var minus = sldid + "_minus";

        // use touch events on iPhone or iPad, mouse events otherwise
        var dnevent = PT.isiOS == true ? 'touchstart' : 'mousedown';
        var upevent = PT.isiOS == true ? 'touchend' : 'mouseup mouseleave';

        $(plus).bind(dnevent, function(e) {
            $(plus).everyTime(100,"sliderbutton", function(){
                $(sldid).trigger('incr');
                // console.log("mousedown Plus");
                })
            });
        $(plus).bind(upevent,function(e){
                $(plus).stopTime("sliderbutton");
                //console.log("mouseup Plus");
            });

        $(minus).bind(dnevent, function(e) {
            $(minus).everyTime(100,"sliderbutton", function(){
                $(sldid).trigger('decr');
                })
            });
        $(minus).bind(upevent,function(e){
                $(minus).stopTime("sliderbutton");
            });

        };        

    // Sparkline update function
    function updatesparklines() {
        var url = PT.jsonurl +
            '/' + PT.lastmodified +
            '/' + PT.lastresponse;

        $.getJSON(url, function(data) {
            if (PT.lastmodified != data.lastmodified) {
                alert("New items added. Will reload now.");
                PT.lastmodified = data.lastmodified;
                location.reload();
            }
            PT.schartoptions.chartRangeMax = data.nmax;
            PT.cchartoptions.chartRangeMax = data.nmax;
            $('#nresponses').text(data.nmax.toString());
            $('#nparticipants').text(data.nparticipants.toString());
            var yellowflag = false; // initial assumption
            // Update criterion charts    
            for (var k in PT.c) {
                id = "#"+k;
                var score = data.crankingd[k].toFixed(3);
                $(id).sparkline(data.c[k], PT.cchartoptions);
                $(id).bt("Mean weight: "+score);
                var nresponses = data.c[k].sum();
                if (nresponses < data.nmax){
                    yellowflag = true
                    };
                var ndelvotes = data.delvotes.cvotes[k];
                wedges = pievalues(data.nparticipants, nresponses, ndelvotes);
                $(id+"countpie").sparkline(wedges, PT.countpieoptions);
                $(id+"countpie").bt(countpietip(nresponses,
                                                    data.nmax,
                                                    data.nparticipants,
                                                    ndelvotes));
                };
            // Update per-criterion solution charts    
            for (var ks in PT.wsc) { 
                var cd = PT.wsc[ks];
                for (var kc in cd) {  
                    $("#"+ks+kc).sparkline(data.wsc[ks][kc], PT.schartoptions);
                    $("#"+ks+kc+"_raw").sparkline(data.sc[ks][kc], PT.schartoptions);
                    };
                };
            // Update solution charts
            for (var k in PT.s) {
                $("#"+k).sparkline(data.s[k], PT.schartoptions);
                var score = data.srankingd[k].toFixed(3);
                $("#"+k).bt(solutionbartip(score));
                var nresponses = data.s[k].sum();
                var ndelvotes = data.delvotes.svotes[k];
                if (yellowflag == true) {
                    var options = $.extend(true,{}, PT.countpieoptions); //copy
                    options.sliceColors[1] = 'yellow';
                } else {var options = PT.countpieoptions}; //reference
                wedges = pievalues(data.nparticipants, nresponses, ndelvotes);
                $("#"+k+"countpie").sparkline(wedges, options);
                $("#"+k+"countpie").bt(countpietip(nresponses,
                                                    data.nmax,
                                                    data.nparticipants,
                                                    ndelvotes));
                }  
            });
        };
    // Update loop   
    if (PT.mode == "RESULTS") {
        $(function() {
            var inext = 1;
            var count = 1;
            $(this).everyTime(1000,function(inow) {
                // inow = i;
                //console.log(inow,inext)
                assert(inext >= inow, 
                    "inow,inext = "+inow.toString()+"," 
                    + inext.toString());
                $('#updatecountdown').text(inext - inow);
                if((inow >= inext) || PT.updatenow) {
                    PT.updatenow = false;
                    fadeinout('#readout');
                    updatesparklines();
                    count += 1;
                    inext = inow + count + 1;   
                    //console.log(inow, inext, count);
                    } 
                });    
            });
    };
    // jQuery show/hide for entire class of resultdetails
    $(document).ready(function() {
        var junkcanvas = document.createElement('canvas');

        // Determine if we are on iPhone or iPad
        // Adapted from Raul Sanchez 
        // http://www.sanraul.com/lang/en/2010/08/01/implementing-doubletap-on-iphones-and-ipads/
	    PT.isiOS = false;
	    var agent = navigator.userAgent.toLowerCase();
	    if(agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0){
	       PT.isiOS = true;
	    }
        //console.log(String(PT.isiOS));
        if (PT.mode == "RESULTS") {
            $('.helppie').sparkline('html', PT.countpieoptions);
            var ypopts = $.extend(true,{}, PT.countpieoptions); //copy
            ypopts.sliceColors[1] = 'yellow';
            $('.helppie_yellow').sparkline('html', ypopts);
            var sopts = PT.schartoptions;
            sopts.chartRangeMax = 10;
            $('.help_schart').sparkline('html', sopts);
            var copts = PT.cchartoptions;
            copts.chartRangeMax = 10;
            $('.help_cchart').sparkline('html', copts);
            $('#pagetitle').click(function(){
                $('.resultdetails').toggle();
                $.sparkline_display_visible(); 
                fadeinout('#problemtitle');
               });
            $('#pagetitle').dblclick(function(){
                // force all matches to show.
                // useful if some have been individually hidden
                $('.resultdetails').show();
                $.sparkline_display_visible(); 
                fadeinout('#problemtitle');
               });
            $('#readout').bt("Click to update now.",{positions: ['left','bottom']});
            }
        else if (PT.mode == "RESPOND") {
            $('.itemicon').show()
            var ids =  PT.solutionsliderinputs;
            for (var i=0; i<ids.length; i++) {
                sliderinit(ids[i],-1.0,1.0);
                }
            ids =  PT.criterionsliderinputs;
            for (var i=0; i<ids.length; i++) {
                sliderinit(ids[i],0.0,1.0);
                }      
            }
        else if (PT.mode == "EDIT") {
            $('.newitemicon').bt(PT.T.newitemicontip);
            $('.olditemicon').bt(PT.T.olditemicontip);
            }
        $('.clickable.itemlabel').bt(PT.T.fulltexttip);
        $('.commentlink').bt(PT.T.commenttip);

    });
    /* ]]> */
</script> 
